package com.example.jin.des;

import static com.example.jin.des.ByteUtil.StringToHex;

/**
 * Created by Jin on 2018/1/17.
 */

public class CmdManager {

    private static CmdManager manager;

    private CmdManager() {
    }

    public static CmdManager getInstance() {
        if (manager == null) {
            manager = new CmdManager();
        }
        return manager;
    }

    /**
     * 生成交换命令
     *
     * @param key 前半段key 即Key1
     * @return cmd
     */
    public static byte[] buildExchangeCmd(byte[] key) {
        byte[] suffer = new byte[]{(byte) 0xFF, (byte) 0xA0, 0x00, 0x08, 0x08};
        byte[] data;
        try {
            DesUtil.TripleDes_Encryption(key, Constants.ROOT_KEY);
            data = ByteUtil.byteContact(suffer, key);
        } catch (Exception e) {
            e.printStackTrace();
            data = null;
        }
        DesUtil.TripleDes_Decryption(key, Constants.ROOT_KEY);
        return data;
    }


    /**
     * 生成指令
     *
     * @param content 明文信息
     * @param key 完整key
     * @return cmd
     */
    public static String buildAPDUAsciiCmd(String content, byte[] key) {

        byte[] data = StringToHex(content);
        byte[] ming;
        int count = data.length / 8;
        int remain = data.length % 8;
        if (remain == 0) {
            ming = new byte[data.length];
        } else {
            ming = new byte[count * 8 + 8];
        }

        System.arraycopy(data, 0, ming, 0, data.length);
        try {
            DesUtil.TripleDes_Encryption(ming, key);
            byte[] suffer = new byte[]{(byte) 0xFF, (byte) 0xA1, 0x00, (byte) data.length, (byte) ming.length};
            String cmd = ByteUtil.HexToString(ByteUtil.byteContact(suffer, ming));
            return cmd;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
